#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QNetworkProxy>
#include <QNetworkReply>
#include <QBuffer>
#include <QUrl>
#include "parser.h"
#include <QInputDialog>


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    first = true;
    ui->setupUi(this);
    messagebox = new MessageBox(this);
    ui->verticalLayout->addWidget(messagebox);

    thread = new UpdateThread(this, 0);
    connect(thread,SIGNAL(dataReceived(QByteArray)),this,SLOT(writeData(QByteArray)));
    connect(messagebox,SIGNAL(returnPressed()),this,SLOT(sendMessage()));
    connect(ui->toolButton,SIGNAL(clicked()),this,SLOT(changeUserStatus()));
    connect(ui->toolButton_bold,SIGNAL(clicked()),this,SLOT(bold()));
    connect(ui->toolButton_italic,SIGNAL(clicked()),this,SLOT(italic()));
    connect(ui->toolButton_underlined,SIGNAL(clicked()),this,SLOT(underlined()));
    //this->setVisible(false);
    connect(ui->textBrowser,SIGNAL(anchorClicked(QUrl)),this,SLOT(anchorClicked(QUrl)));
    icon = new QSystemTrayIcon(this);
    icon->setIcon(QIcon(":/icons/typing.png"));
    icon->setVisible(true);
    icon->show();
    connect(icon,SIGNAL(activated(QSystemTrayIcon::ActivationReason)),this,SLOT(maximazieFromTray(QSystemTrayIcon::ActivationReason)));

    //ui->textBrowser->setText("<a href='http://google.de'>klick</a>");
    //ui->textBrowser->append("<a href='http://google.de'><b>klick</b></a>\n");
    m_pHideTimer = new QTimer(this);
    m_pHideTimer->setInterval(10);
    m_pHideTimer->setSingleShot(true);
    connect(m_pHideTimer, SIGNAL(timeout()), this, SLOT(hide()));
    //this->removeDockWidget(ui->webdock);
    ui->webdock->setVisible(false);
    //connect(ui->webdock,SIGNAL(visibilityChanged(bool)),this,SLOT(dockVisibilityChanged(bool)));
    thread->setIntervall(400);
}

MainWindow::~MainWindow()
{
    //disconnect(thread,SIGNAL(dataReceived(QByteArray)),this,SLOT(writeData(QByteArray)));
    //delete thread;
    //disconnect(this);
    //delete ui;
}

void MainWindow::showUserDialog()
{
    http = new Http();
    connect(http,SIGNAL(dataReceived(QByteArray)),this,SLOT(registerUser(QByteArray)));
    QString url_str = "http://84.200.214.165/register.php?nick=";
    registerDialog dial(this);
    dial.exec();
    me.nick = dial.getText();
    url_str += QUrl::toPercentEncoding(dial.getText());
    QUrl tmp_url(url_str);
    http->getUrl(tmp_url);
    messagebox->setFocus();
}

void MainWindow::download()
{
    //QUrl url("http://84.200.214.165/getUpdate.php?event_id=0");
    //http->getUrl(url);
    thread->start();
}

void MainWindow::writeData(QByteArray array)
{
    QString errorMsg;
    QByteArray arr = QUrl::toPercentEncoding(QString(array));
    QDomNodeList list = Parser::elementsByTagName(array,"evt");
    bool alert_quest = false;
    for(int i = 0; i < list.size();i++)
    {
        QDomNode node = list.at(i);
        if (node.attributes().namedItem("usrId").nodeValue().toInt() != me.id)
            alert_quest = true;
        if(node.attributes().namedItem("typeId").nodeValue().toInt()== 3)
        {
            id = node.attributes().namedItem("id").nodeValue().toInt();
            QString msg = "[";
            msg += node.attributes().namedItem("time").nodeValue();
            msg += "] ";
            msg += userVec.getNickById(node.attributes().namedItem("usrId").nodeValue().toInt());
            msg += "> ";
            thread->setId(id);
            node = node.firstChild();
            msg += QUrl::fromPercentEncoding(node.nodeValue().toUtf8());
            ui->textBrowser->append(msg);

            //qDebug() << ui->textBrowser->toHtml();

        } else if(node.attributes().namedItem("typeId").nodeValue().toInt()== 0)
        {
            user tmpUser;
            tmpUser.id = node.attributes().namedItem("usrId").nodeValue().toInt();
            if(tmpUser.id != me.id)
            {
                tmpUser.nick = node.firstChild().nodeValue();
                tmpUser.statusMessage = "";
                userVec.append(tmpUser);
                QListWidgetItem *item = new QListWidgetItem;
                item->setIcon(QIcon(":/icons/online.png"));
                item->setText(tmpUser.nick);
                ui->listWidget->addItem(item);
                thread->setId(node.attributes().namedItem("id").nodeValue().toInt());
                QString usr_str = "[";
                usr_str += node.attributes().namedItem("time").nodeValue();
                usr_str += "] ";
                usr_str += tmpUser.nick;
                usr_str += ">> hat den Chat betreten";
                ui->textBrowser->append(usr_str);
            }
            else
            {
                thread->setId(node.attributes().namedItem("id").nodeValue().toInt());
                ui->textBrowser->insertPlainText("welcome to bijou - a simple http-chat\n\n\n");

                //ui->textBrowser->append("click <a href='https://code.google.com/p/bijou/'>here</a> for more information");
            }
        } else if(node.attributes().namedItem("typeId").nodeValue().toInt()== 1)
        {

          int usr_id = node.attributes().namedItem("usrId").nodeValue().toInt();
          if(usr_id== me.id)
          {
              QMessageBox msgBox;
              msgBox.setText("You have been kicked by the admin.");
              msgBox.exec();
              QMainWindow::close();
          }
          QString left_str = "[";
          left_str += node.attributes().namedItem("time").nodeValue();
          left_str += "] ";
          left_str += userVec.getNickById(usr_id);
          left_str += ">> hat den chat verlassen";
          ui->textBrowser->append(left_str);
          thread->setId(node.attributes().namedItem("id").nodeValue().toInt());
          userVec.deleteUserById(usr_id);
          ui->listWidget->clear();
          for(int i = 0; i < userVec.size();i++)
          {
              QString usrStr = userVec.at(i).nick;
              QListWidgetItem *item = new QListWidgetItem;
              item->setIcon(QIcon(":/icons/online.png"));
              if(QString::compare(userVec.at(i).statusMessage, ""))
              {
                  item->setIcon(QIcon(":/icons/away.png"));
                  usrStr += "(";
                  usrStr += QUrl::fromPercentEncoding(userVec.at(i).statusMessage.toStdString().c_str());
                  usrStr += ")";
              }
              item->setText(usrStr);
              ui->listWidget->addItem(item);
          }
        } else if(node.attributes().namedItem("typeId").nodeValue().toInt()== 2)
        {
            int usr_id = node.attributes().namedItem("usrId").nodeValue().toInt();

            thread->setId(node.attributes().namedItem("id").nodeValue().toInt());
            QString offstr = "[";
            offstr += node.attributes().namedItem("time").nodeValue();
            offstr += "] ";
            offstr += userVec.getNickById(usr_id);
            if(QString::compare(list.at(0).firstChild().nodeValue(), ""))
            {
                offstr += ">> ist abwesend: ";
                offstr += QUrl::fromPercentEncoding(list.at(0).firstChild().nodeValue().toStdString().c_str());
            } else
            {
                offstr += ">>  ist nicht mehr abwesend";
            }
            ui->textBrowser->append(offstr);
            userVec.changeUserStatusById(usr_id,2,list.at(0).firstChild().nodeValue().toStdString().c_str());

            ui->listWidget->clear();
            for(int i = 0; i < userVec.size();i++)
            {
                QString usrStr = userVec.at(i).nick;
                QListWidgetItem *item = new QListWidgetItem;
                item->setIcon(QIcon(":/icons/online.png"));
                if(QString::compare(userVec.at(i).statusMessage, ""))
                {
                    item->setIcon(QIcon(":/icons/away.png"));
                    usrStr += "(";
                    usrStr += QUrl::fromPercentEncoding(userVec.at(i).statusMessage.toStdString().c_str());
                    usrStr += ")";
                }
                item->setText(usrStr);
                ui->listWidget->addItem(item);
            }
        }
    }

    if(alert_quest&& this->isActiveWindow()==false)
    {
        Phonon::MediaObject *mediaObject = new Phonon::MediaObject(this);

        Phonon::MediaObject *music =
            Phonon::createPlayer(Phonon::MusicCategory,
                                 Phonon::MediaSource("C:\\Qt\\2010.04\\chat_prototype_0.9\\sounds\\in.wav"));
        music->play();


        //mediaObject->setCurrentSource(Phonon::MediaSource("C:\\Qt\\2010.04\\chat_prototype_0.9\\sounds\\incoming.mp3"));//":/sounds/incoming.mp3"));
        //    Phonon::AudioOutput *audioOutput =
        //        new Phonon::AudioOutput(Phonon::MusicCategory, this);
        //    Phonon::Path path = Phonon::createPath(mediaObject, audioOutput);
        QApplication::alert(this);
    }

}

void MainWindow::sendMessage()
{
    if(QString::compare(messagebox->text(),""))
    {
        event_struct tmpEv;
        tmpEv.type_id = 3;
        tmpEv.value = QUrl::toPercentEncoding(QByteArray(messagebox->text().toStdString().c_str()));
        messagebox->clear();
        eventVec.append(tmpEv);
        if(eventVec.size() == 1)
            sendOne();
    }
}

void MainWindow::sendOne()
{
    http = new Http();
    QString url_str = "http://84.200.214.165/sendEvent.php?event_type_id=";
    url_str += QString::number(eventVec.at(0).type_id);
    url_str += "&user_id=";
    url_str += QString::number(me.id);
    url_str += "&value=";
    url_str += eventVec.at(0).value;
    QUrl url(url_str);
    connect(http,SIGNAL(dataReceived(QByteArray)),this,SLOT(sended(QByteArray)));
    http->getUrl(url);
}

void MainWindow::sended(QByteArray array)
{
    disconnect(http,SIGNAL(dataReceived(QByteArray)),this,SLOT(sended(QByteArray)));
    eventVec.remove(0);
    if(eventVec.size() > 0)
        sendOne();
}

void MainWindow::registerUser(QByteArray array)
{
    //fill qDict of users
    disconnect(http,SIGNAL(dataReceived(QByteArray)),this,SLOT(registerUser(QByteArray)));
    QString *errorMsg = new QString("");
    QByteArray arr = QUrl::toPercentEncoding(QString(array));
    QDomNodeList list = Parser::elementsByTagName(array,"srv",errorMsg);
    me.id = list.at(0).attributes().namedItem("usr_id").nodeValue().toInt();
    me.statusMessage = "";
    me.status_id = 0;
    userVec.append(me);
    QString usr_str = me.nick;
    QListWidgetItem *item = new QListWidgetItem;
    item->setIcon(QIcon(":/icons/online.png"));
    item->setText(usr_str);
    ui->listWidget->addItem(item);

    list = Parser::elementsByTagName(array,"usr",errorMsg);

    for(int i = 0; i < list.size();i++)
    {
        user cu;
        QDomNode node = list.at(i);

        cu.id = node.attributes().namedItem("id").nodeValue().toInt();
        if(id != me.id)
        {
            cu.status_id = node.attributes().namedItem("statusId").nodeValue().toInt();
            cu.statusMessage = node.attributes().namedItem("statusValue").nodeValue();

            node = node.firstChild();
            cu.nick = node.nodeValue();
            QString usr_str = cu.nick;
            QListWidgetItem *item = new QListWidgetItem;
            item->setIcon(QIcon(":/icons/online.png"));
            if(cu.status_id)
            {
                item->setIcon(QIcon(":/icons/away.png"));
                usr_str += "(";
                usr_str += QUrl::fromPercentEncoding(cu.statusMessage.toStdString().c_str());
                usr_str += ")";
            }
            item->setText(usr_str);
            ui->listWidget->addItem(item);
            userVec.append(cu);

        }
    }
    download();
}

void MainWindow::closeEvent ( QCloseEvent * e )
{
    if(http)
    {
        connect(http,SIGNAL(dataReceived(QByteArray)),this,SLOT(logout(QByteArray)));
        QString url_str = "http://84.200.214.165/logout.php?user_id=";
        url_str += QString::number(me.id);
        QUrl tmp_url(url_str);
        http->getUrl(tmp_url);
        e->ignore();
    }
}

void MainWindow::logout(QByteArray array)
{
    disconnect(http,SIGNAL(dataReceived(QByteArray)),this,SLOT(logout(QByteArray)));
    //delete http;
    http = NULL;
    this->close();
}

void MainWindow::changeUserStatus()
{
    event_struct tmpEv;
    tmpEv.type_id = 2;
    tmpEv.value = "";
    if(ui->toolButton->isChecked())
    {
        QString text = QInputDialog::getText(this, tr("Abwesenheitsnotiz"),
                                              tr("Abwesenheitsnotiz:"), QLineEdit::Normal,
                                              "@");


        tmpEv.value = QUrl::toPercentEncoding(QByteArray(text.toStdString().c_str()));

        //ui->toolButton->setChecked(true);
    }
   // else ui->toolButton->setChecked(false);
    eventVec.append(tmpEv);
    if(eventVec.size() == 1)
        sendOne();
}

void MainWindow::bold()
{
    if(ui->toolButton_bold->isChecked())
        messagebox->insertPlainText("<b>");
    else
        messagebox->insertPlainText("</b>");
}

void MainWindow::italic()
{
    if(ui->toolButton_italic->isChecked())
        messagebox->insertPlainText("<i>");
    else
        messagebox->insertPlainText("</i>");
}

void MainWindow::underlined()
{
    if(ui->toolButton_underlined->isChecked())
        messagebox->insertPlainText("<u>");
    else
        messagebox->insertPlainText("</u>");
}

void MainWindow::anchorClicked(const QUrl & link)
{
    //this->addDockWidget(Qt::RightDockWidgetArea,ui->webdock);
    //ui->webdock->setVisible(true);
    //ui->webView->setUrl(link);
    //qDebug() <<"here";

    qDebug() <<ui->textBrowser->toHtml();
    //ui->textBrowser->setCurrentCharFormat(format);
    ui->textBrowser->append("</a>test");
   // ui->webView
    //ui->textBrowser->setCurrentCharFormat(format);
}

void MainWindow::maximazieFromTray(QSystemTrayIcon::ActivationReason reason)
{
    show ();
    activateWindow ();
    showNormal ();
    messagebox->setFocus();
    thread->setIntervall(300);
}

void MainWindow::hideEvent (QHideEvent * event)
{
        QWidget::hideEvent(event);

                m_pHideTimer->start();
                thread->setIntervall(30000);
}

bool MainWindow::event(QEvent *event)
{
    if (event->type() == QEvent::WindowDeactivate)
        thread->setIntervall(15000);
    else if(event->type() == QEvent::WindowActivate)
    {
        thread->setIntervall(300);
        if(!first)
            thread->resetTimer();
        else
            first = false;
    }
    return QMainWindow::event(event);
}

void MainWindow::dockVisibilityChanged(bool visible)
{
    if (visible)
    {
        switch(dockWidgetArea(ui->webdock))
        {
        case Qt::LeftDockWidgetArea :
            this->setGeometry(this->x()-10,this->y()-10,this->width()+ui->webdock->width(),this->height());
            break;
        case Qt::RightDockWidgetArea :
            this->setGeometry(this->x()-10,this->y()-10,this->width()+ui->webdock->width(),this->height());
            break;
        case Qt::TopDockWidgetArea :
            this->setGeometry(this->x()-10,this->y()-10,this->width(),this->height()+ui->webdock->height());
            break;
        case Qt::BottomDockWidgetArea:
            this->setGeometry(this->x()-10,this->y()-10,this->width(),this->height()+ui->webdock->height());
            break;
        }
    }
    else
    {
        switch(dockWidgetArea(ui->webdock))
        {
        case Qt::LeftDockWidgetArea :
            this->setGeometry(this->x()-10,this->y()-10,this->width()-ui->webdock->width(),this->height());
            break;
        case Qt::RightDockWidgetArea :
            this->setGeometry(this->x()-10,this->y()-10,this->width()-ui->webdock->width(),this->height());
            break;
        case Qt::TopDockWidgetArea :
            this->setGeometry(this->x()-10,this->y()-10,this->width(),this->height()-ui->webdock->height());
            break;
        case Qt::BottomDockWidgetArea:
            this->setGeometry(this->x()-10,this->y()-10,this->width(),this->height()-ui->webdock->height());
            break;
        }
    }
}
